<template>
  <div class="profile">
    <div class="account-settings-info-title">
      <span data-v-26b608e6="">基本资料</span>
    </div>
    <div class="account-settings-info-view">
      <avue-form
        ref="form"
        v-model="form"
        :option="options"
        :upload-delete="uploadDelete"
        :upload-before="uploadBefore"
        :upload-after="uploadAfter"
        @submit="handleSubmit"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import upload from '@/api/sys/upload'
import { uniqueStr } from '@/util/NumberUtil'

const delFileAction = 'sys/upload/deleteFile'
const userUpdateAction = 'sys/user/updateUser'
const updateUserInfoAction = 'sys/user/updateUserInfo'
// const activeUserTabAction = 'app/switchUserCenterActiveTab'
export default {
  name: 'Basic',
  data () {
    return {
      uploadToken: '',
      form: {},
      options: {
        emptyBtn: false,
        column: [
          {
            label: '头像',
            prop: 'avatar',
            type: 'upload',
            accept: ['image/jpeg', 'image/png'],
            limit: 1,
            // 此处选项如果是listType =picture-img不用添加
            // dataType: 'string',
            listType: 'picture-img',
            tip: '只能上传jpg/png用户头像，且不超过500kb',
            canvasOption: {
              text: '头像',
              ratio: 0.1
            },
            action: upload.UPLOAD_URL,
            data: {
              userId: 0,
              token: ''
            },
            propsHttp: {
              res: 'data',
              url: 'url'
            },
            span: 24,
            // 此处是字节单位,注意
            filesize: 512000,
            rules: [{
              required: false,
              message: '请上传头像',
              trigger: 'blur'
            }]
          },
          {
            label: '用户名',
            prop: 'userName',
            span: 24,
            showWordLimit: true,
            disabled: true,
            maxlength: 30,
            rules: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            }]
          },
          {
            label: '昵称',
            prop: 'nickName',
            span: 24,
            showWordLimit: true,
            maxlength: 30,
            rules: [{
              required: true,
              message: '请输入昵称',
              trigger: 'blur'
            }]
          },
          {
            label: '性别',
            prop: 'sex',
            type: 'radio',
            span: 24,
            dicData: [{ label: '男', value: 1 }, { label: '女', value: 2 }, { label: '未知', value: 3 }],
            value: 3,
            rules: [{
              required: false,
              message: '请输入性别',
              trigger: 'blur'
            }]
          },
          {
            label: '出生日期',
            prop: 'birth',
            type: 'date',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            pickerOptions: {
              disabledDate (time) {
                return time.getTime() >= Date.now()
              }
            },
            span: 24,
            rules: [{
              required: false,
              message: '请输入出生日期',
              trigger: 'blur'
            }]
          },
          {
            label: '签名',
            prop: 'signature',
            type: 'textarea',
            span: 24,
            showWordLimit: true,
            maxlength: 200,
            rules: [{
              required: false,
              message: '请输入签名',
              trigger: 'blur'
            }]
          },
          {
            label: '地址',
            prop: 'address',
            maxlength: 200,
            span: 24,
            showWordLimit: true,
            rules: [{
              required: false,
              message: '请输入地址',
              trigger: 'blur'
            }]
          }
        ]
      }
    }
  },
  computed: { ...mapGetters(['userInfo', 'token']) },
  mounted () {
    // 设置激活的用户中心tab标签
    // this.$store.dispatch(activeUserTabAction, 'basic')
    // 设置对应的用户的头像相关上传信息
    this.form = this.userInfo
    const index = this.$refs.form.findColumnIndex('avatar')
    this.options.column[index].data = {
      userId: this.userInfo.id,
      token: uniqueStr()
    }
  },
  methods: {
    // 上传相关
    uploadBefore (file, done, loading) {
      // 如果你想修改file文件,由于上传的file是只读文件，必须复制新的file才可以修改名字，完后赋值到done函数里,如果不修改的话直接写done()即可
      // const newFile = new File([file], '1234', { type: file.type })
      done(file)
    },
    uploadAfter (res, done, loading) {
      // console.log('done: ', res)
      // const fileId = res.id
      // const index = this.$refs.crud.findColumnIndex('avatar')
      // this.option.column[index].fileId = fileId
      done()
    },
    uploadDelete (column) {
      const avatar = this.form.avatar
      return this.$confirm('是否确定移除头像？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const delData = { url: avatar }
        return this.$store.dispatch(delFileAction, delData)
      }).then((res) => {
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.$message({
            type: 'success',
            message: '删除头像成功!'
          })
          return true
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '删除头像失败,请稍后再试!'
          })
          return false
        }
      }).catch(() => {
        return false
      })
    },
    handleSubmit (form, done) {
      const updateFormData = {
        id: this.userInfo.id,
        avatar: form.avatar,
        userName: form.userName,
        nickName: form.nickName,
        sex: form.sex,
        birth: form.birth,
        signature: form.signature,
        address: form.address,
        token: this.token
      }
      this.$store.dispatch(userUpdateAction, updateFormData).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const updateUserInfo = {
            avatar: form.avatar,
            userName: form.userName,
            nickName: form.nickName,
            sex: form.sex,
            birth: form.birth,
            signature: form.signature,
            address: form.address
          }
          this.$store.dispatch(updateUserInfoAction, updateUserInfo).then(() => {
            this.$message({
              type: 'success',
              message: '更新用户资料成功!'
            })
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '更新数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    }
  },
  head () {
    return {
      title: '基本资料 | 个人中心',
      meta: [
        { hid: 'description', name: 'description', content: '个人资料,个人中心' }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
.profile {
  flex: 1 1;
  padding: 8px 40px;

  .account-settings-info-title {
    color: rgba(0,0,0,.85);
    font-size: 20px;
    font-weight: 500;
    line-height: 28px;
    margin-bottom: 12px;
  }
  .account-settings-info-view {
    padding-top: 12px;
  }
}
</style>
